package com.zxy.ziems.server.utils;

import com.zxy.btp.common.response.JsonResponse;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.io.File;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class OkHttpUtil {
    public static final MediaType JSON = MediaType.parse("application/json;charset=utf-8");
    public static final MediaType TEXT_PLAIN = MediaType.parse("text/plain");
    public static final MediaType OCTET_STREAM = MediaType.parse("application/octet-stream");
    private static final OkHttpClient CLIENT = buildOkHttpClient();
    private static final Logger LOG = LoggerFactory.getLogger(OkHttpUtil.class);

    public OkHttpUtil() {
    }

    private static OkHttpClient.Builder getBuilder() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.readTimeout(10L, TimeUnit.MINUTES);
        builder.connectTimeout(10L, TimeUnit.MINUTES);
        builder.writeTimeout(10L, TimeUnit.MINUTES);
        builder.retryOnConnectionFailure(true);
        ConnectionPool connectionPool = new ConnectionPool(50, 5L, TimeUnit.MINUTES);
        builder.connectionPool(connectionPool);
        List<Protocol> protocols = new ArrayList();
        protocols.add(Protocol.HTTP_1_1);
        protocols.add(Protocol.HTTP_2);
        builder.protocols(protocols);
        return builder;
    }

    public static OkHttpClient buildOkHttpClient() {
        OkHttpClient.Builder builder = getBuilder();
        OkHttpClient okHttpClient = builder.build();
        return okHttpClient;
    }

    public static OkHttpClient buildSslOkHttpClient() {
        try {
            X509TrustManager trustManager = new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] arg0, String arg1) {
                }

                public void checkServerTrusted(X509Certificate[] arg0, String arg1) {
                }

                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            };
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init((KeyManager[])null, new TrustManager[]{trustManager}, new SecureRandom());
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            OkHttpClient.Builder builder = getBuilder();
            builder.sslSocketFactory(sslSocketFactory, trustManager);
            builder.hostnameVerifier(new HostnameVerifier() {
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            OkHttpClient okHttpClient = builder.build();
            return okHttpClient;
        } catch (Exception var5) {
            LOG.error("buildSslOkHttpClient error", var5);
            return null;
        }
    }

    public static Headers buildHeaders(Map<String, String> params) {
        Headers headers = null;
        Headers.Builder headerBuilder = new Headers.Builder();
        Iterator var3 = params.keySet().iterator();

        while(var3.hasNext()) {
            String key = (String)var3.next();
            headerBuilder.add(key, (String)params.get(key));
        }

        headers = headerBuilder.build();
        return headers;
    }

    public static String get(String url, Map<String, String> params) throws Exception {
        return get(url, params, (Map)null);
    }

    public static String get(String url, Map<String, String> params, Map<String, String> headers) throws Exception {
        JsonResponse<String> okResponse = getText(url, params, headers);
        return okResponse.getData();
    }

    public static JsonResponse<String> getText(String url, Map<String, String> params, Map<String, String> headers) throws Exception {
        StringBuilder realUrl = new StringBuilder(url);
        if (params != null && !params.isEmpty()) {
            realUrl.append("?");
            Iterator var4 = params.keySet().iterator();

            while(var4.hasNext()) {
                String key = (String)var4.next();
                realUrl.append(key).append("=").append((String)params.get(key)).append("&");
            }

            realUrl.deleteCharAt(realUrl.length() - 1);
        }

        LOG.debug("get url -> {}, headers->{}", realUrl.toString(), headers);
        Request.Builder builder = new Request.Builder();
        builder.url(realUrl.toString());
        if (headers != null && !headers.isEmpty()) {
            Headers okHeaders = buildHeaders(headers);
            builder.headers(okHeaders);
        }

        Request request = builder.build();
        Response response = CLIENT.newCall(request).execute();
        String body = new String(response.body().bytes(), "UTF-8");
        int code = response.code();
        LOG.debug("response code-> {}, body->{}", code, body);
        return new JsonResponse(code, "", body);
    }

    public static String postJson(String url, String json) throws Exception {
        return postJson(url, json, (Map)null);
    }

    public static String postJson(String url, String json, Map<String, String> headers) throws Exception {
        JsonResponse<String> okResponse = jsonPost(url, json, headers);
        return okResponse.getData();
    }

    public static JsonResponse<String> jsonPost(String url, String json, Map<String, String> headers) throws Exception {
        LOG.debug("postJson url->{}, json->{}, headers->{}", new Object[]{url, json, headers});
        RequestBody requestBody = RequestBody.create(JSON, json);
        Request.Builder builder = new Request.Builder();
        builder.url(url);
        if (headers != null && !headers.isEmpty()) {
            Headers okHeaders = buildHeaders(headers);
            builder.headers(okHeaders);
        }

        builder.post(requestBody);
        Request request = builder.build();
        Response response = CLIENT.newCall(request).execute();
        String body = new String(response.body().bytes(), "UTF-8");
        int code = response.code();
        LOG.debug("response code-> {}, body->{}", code, body);
        return new JsonResponse<String>(code, "", body);
    }

    public static String postStream(String url) throws Exception {
        return postStream(url, (String)null);
    }

    public static String postStream(String url, String text) throws Exception {
        return postStream(url, text, (Map)null);
    }

    public static String postStream(String url, String text, Map<String, String> headers) throws Exception {
        JsonResponse<String> okResponse = streamPost(url, text, headers);
        return okResponse.getData();
    }

    public static JsonResponse<String> streamPost(String url, String text, Map<String, String> headers) throws Exception {
        LOG.debug("postStream url->{}, json->{}, headers->{}", new Object[]{url, text, headers});
        Request.Builder builder = new Request.Builder();
        builder.url(url);
        if (headers != null && !headers.isEmpty()) {
            Headers okHeaders = buildHeaders(headers);
            builder.headers(okHeaders);
        }

        if (text != null) {
            RequestBody requestBody = RequestBody.create(TEXT_PLAIN, text);
            builder.post(requestBody);
        }

        Request request = builder.build();
        Response response = CLIENT.newCall(request).execute();
        String body = new String(response.body().bytes(), "UTF-8");
        int code = response.code();
        LOG.debug("response code-> {}, body->{}", code, body);
        return new JsonResponse<String>(code, "", body);
    }

    public static String postSslStream(OkHttpClient okHttpClient, String url, String text) throws Exception {
        return postSslStream(okHttpClient, url, text, (Map)null);
    }

    public static String postSslStream(OkHttpClient okHttpClient, String url, String text, Map<String, String> headers) throws Exception {
        JsonResponse<String> okResponse = sslStreamPost(okHttpClient, url, text, headers);
        return okResponse.getData();
    }

    public static JsonResponse<String> sslStreamPost(OkHttpClient okHttpClient, String url, String text, Map<String, String> headers) throws Exception {
        LOG.debug("postStream url->{}, json->{}, headers->{}", new Object[]{url, text, headers});
        RequestBody requestBody = RequestBody.create(TEXT_PLAIN, text);
        Request.Builder builder = new Request.Builder();
        builder.url(url);
        if (headers != null && !headers.isEmpty()) {
            Headers okHeaders = buildHeaders(headers);
            builder.headers(okHeaders);
        }

        builder.post(requestBody);
        Request request = builder.build();
        Response response = okHttpClient.newCall(request).execute();
        String body = new String(response.body().bytes(), "UTF-8");
        int code = response.code();
        LOG.debug("response code-> {}, body->{}", code, body);
        return new JsonResponse<String>(code, "", body);
    }

    public static String postFile(String url, Map<String, File> fileMap) throws Exception {
        return postFile(url, (Map)null, fileMap, (Map)null);
    }

    public static String postFile(String url, Map<String, String> params, Map<String, File> fileMap) throws Exception {
        return postFile(url, params, fileMap, (Map)null);
    }

    public static String postFile(String url, Map<String, String> params, Map<String, File> fileMap, Map<String, String> headers) throws Exception {
        JsonResponse<String> okResponse = filePost(url, params, fileMap, headers);
        return okResponse.getData();
    }

    public static JsonResponse<String> filePost(String url, Map<String, String> params, Map<String, File> fileMap, Map<String, String> headers) throws Exception {
        LOG.debug("postStream url->{}, params->{}, fileMap->{}, headers->{}", new Object[]{url, params, fileMap, headers});
        MultipartBody.Builder builder = (new MultipartBody.Builder()).setType(MultipartBody.FORM);
        Iterator var5;
        String key;
        if (params != null && !params.isEmpty()) {
            var5 = params.keySet().iterator();

            while(var5.hasNext()) {
                key = (String)var5.next();
                builder.addFormDataPart(key, (String)params.get(key));
            }
        }

        if (fileMap != null && !fileMap.isEmpty()) {
            var5 = fileMap.keySet().iterator();

            while(var5.hasNext()) {
                key = (String)var5.next();
                File file = (File)fileMap.get(key);
                RequestBody fileBody = RequestBody.create(OCTET_STREAM, file);
                builder.addFormDataPart(key, file.getName(), fileBody);
            }
        }

        MultipartBody multipartBody = builder.build();
        Request.Builder requestBuiler = new Request.Builder();
        requestBuiler.post(multipartBody);
        if (headers != null && !headers.isEmpty()) {
            Headers okHeaders = buildHeaders(headers);
            requestBuiler.headers(okHeaders);
        }

        requestBuiler.url(url);
        Request request = requestBuiler.build();
        Response response = CLIENT.newCall(request).execute();
        String body = new String(response.body().bytes(), "UTF-8");
        int code = response.code();
        LOG.debug("response code-> {}, body->{}", code, body);
        return new JsonResponse<String>(code, "", body);
    }

    public static String postForm(String url, Map<String, String> params) throws Exception {
        return postForm(url, params, (Map)null);
    }

    public static String postForm(String url, Map<String, String> params, Map<String, String> headers) throws Exception {
        JsonResponse<String> okResponse = formPost(url, params, headers);
        return okResponse.getData();
    }

    public static JsonResponse<String> formPost(String url, Map<String, String> params, Map<String, String> headers) throws Exception {
        LOG.debug("postStream url->{}, params->{}, headers->{}", new Object[]{url, params, headers});
        FormBody.Builder formBuilder = new FormBody.Builder();
        if (params != null && !params.isEmpty()) {
            Iterator var4 = params.keySet().iterator();

            while(var4.hasNext()) {
                String key = (String)var4.next();
                formBuilder.add(key, (String)params.get(key));
            }
        }

        RequestBody formBody = formBuilder.build();
        Request.Builder requestBuiler = new Request.Builder();
        if (headers != null && !headers.isEmpty()) {
            Headers okHeaders = buildHeaders(headers);
            requestBuiler.headers(okHeaders);
        }

        requestBuiler.post(formBody);
        requestBuiler.url(url);
        Request request = requestBuiler.build();
        Response response = CLIENT.newCall(request).execute();
        String body = new String(response.body().bytes(), "UTF-8");
        int code = response.code();
        LOG.debug("response code->{}, body-> {}", code, body);
        return new JsonResponse<String>(code, "", body);
    }
}
